<!-- 编辑/新增收货地址的卡片 -->
<template>
  <el-card v-loading="loading" shadow="never" class="addr-card">
    <el-form ref="addressFormRef" :model="my_address" label-width="120px" :rules="rules">
      <!-- 收货人 -->
      <el-form-item prop="name">
        <template #label>
          <div class="addr-label">收货人</div>
        </template>
        <el-input v-model="my_address.name" placeholder="请填写收货人姓名" input-style="font-size: 15px;">
          <template #append>
            <el-icon>
              <font-awesome-icon :icon="['fas', 'user']" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 手机号码 -->
      <el-form-item prop="phoneNumber">
        <template #label>
          <div class="addr-label">手机号码</div>
        </template>
        <el-input v-model="my_address.phoneNumber" placeholder="请填写收货人手机号" input-style="font-size: 15px;">
          <template #append>
            <el-icon>
              <font-awesome-icon :icon="['fas', 'phone']" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 所在地：采用级联选择器 -->
      <el-form-item prop="selectedOptions">
        <template #label>
          <div class="addr-label">所在地区</div>
        </template>
        <el-cascader style="width: 460px;" placeholder="请选择所在地区" clearable @blur='addressBlur' :options="options"
          v-model="selectedOptions" @change="handleChange" />
      </el-form-item>

      <!-- 详细地址 -->
      <el-form-item prop="detail">
        <template #label>
          <div class="addr-label">详细地址</div>
        </template>
        <el-input type="textarea" :rows="3" resize="none" placeholder="请填写详细地址，如街道、楼牌号等" v-model="my_address.detail"
          input-style="font-size: 15px;">
        </el-input>
      </el-form-item>

      <!-- 标签 -->
      <el-form-item>
        <template #label>
          <div class="addr-label">标签</div>
        </template>
        <el-col :span="5">
          <el-input v-model="my_address.tag" placeholder="请填写标签" input-style="text-align: center; font-size: 15px;">
          </el-input>
        </el-col>
      </el-form-item>

      <!-- 是否设为默认地址 -->
      <el-form-item>
        <template #label>
          <div class="addr-label">设为默认地址</div>
        </template>
        <el-radio-group v-model="my_address.isDefault" prop="isDefault">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- tip -->
      <el-form-item>
        <div class="tip">
          <el-icon style="margin-right: 5px;">
            <InfoFilled />
          </el-icon>
          注意：修改后请及时保存，否则修改无法生效
        </div>
      </el-form-item>

      <!-- 保存提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="newlyAdd ? submitAdd() : submitEdit()" style="width: 130px; font-size: 15px;">
          <el-icon style="margin-right: 3px;">
            <font-awesome-icon :icon="['fas', 'location-arrow']" />
          </el-icon>
          保存
        </el-button>
      </el-form-item>

    </el-form>
  </el-card>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance } from "vue"
import { pcaTextArr } from 'element-china-area-data' // 省市区三级联动选择
import { phoneNumber } from '../validator'

const { proxy } = getCurrentInstance();
const options = ref(pcaTextArr);
const selectedOptions = ref([]);
const loading = ref(false);
const addressFormRef = ref(null);

const emit = defineEmits(['opSuccess']);  // 操作成功后的调用父组件的方法

const props = defineProps({  // 可以拿到父组件传入的值
  my_address: {
    "addressId": "",
    "userId": "",
    "name": "",
    "phoneNumber": "",
    "province": "",
    "city": "",
    "district": "",
    "detail": "",
    "tag": "",
    "isDefault": 0
  },
  newlyAdd: false,  // 如果传入true，表示实际上是要新增一个地址
});

// 表单的校验规则
const rules = reactive({
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    {
      validator: phoneNumber, trigger: 'blur'
    },
  ],
  selectedOptions: [
    {
      validator: (rule, value, callback) => {
        console.log("validator: ", selectedOptions.value)
        if (!selectedOptions.value || selectedOptions.value.length !== 3) {
          callback(new Error("请选择所在的地区"));
        } else {
          callback()
        }
      },
      required: true,
      trigger: 'change',
    }
  ],
  detail: [
    { required: true, message: '请输入详细地址，如街道、楼牌号等', trigger: 'blur' },
  ]
})

/**
 * 每次级联选择器发生变化时，重新设置my_address中的省市区
 */
const handleChange = () => {
  if (selectedOptions.value.length > 0) {
    props.my_address.province = selectedOptions.value[0];
    props.my_address.city = selectedOptions.value[1];
    props.my_address.district = selectedOptions.value[2];
  } else {
    props.my_address.province = "";
    props.my_address.city = "";
    props.my_address.district = "";
  }
}

/**
 * 更新收货地址
 */
const submitEdit = async () => {
  let valid = await addressFormRef.value.validate();
  if (valid) {
    loading.value = true;
    let ret = await proxy.$api.address.modifyAddress(props.my_address).catch(error => {
      loading.value = false;
      ElMessage.error({ showClose: true, message: "修改收货地址失败" });
    });
    if (ret.status === 200) {
      ElMessage.success({ showClose: true, message: "修改收货地址成功" });
      emit('opSuccess');
    }
    loading.value = false;
  }
}

/**
 * 增加收货地址
 */
const submitAdd = async () => {
  let valid = await addressFormRef.value.validate();
  if (valid) {
    loading.value = true;
    let ret = await proxy.$api.address.addNewAddress(props.my_address).catch(error => {
      loading.value = false;
      ElMessage.error({ showClose: true, message: "添加收货地址失败" });
    });
    if (ret.status === 200) {
      ElMessage.success({ showClose: true, message: "添加收货地址成功" });
      emit('opSuccess');
    }
    loading.value = false;
  }
}

/**
 * 添加失去焦点触发 validateField	对部分表单字段进行校验的方法
 */
const addressBlur = () => {
  addressFormRef.value.validateField('selectedOptions');
}

/**
  * 清除validate，并设置selectedOptions
  */
const clearValidAndSelOps = () => {
  addressFormRef.value.clearValidate();
  selectedOptions.value = [];
  if (!props.newlyAdd) {
    selectedOptions.value.push(props.my_address.province);
    selectedOptions.value.push(props.my_address.city);
    selectedOptions.value.push(props.my_address.district);
  }
}

defineExpose({ clearValidAndSelOps })

onMounted(() => {
  clearValidAndSelOps();
})
</script>

<style lang="less" scoped>
.addr-card {
  .addr-label {
    font-size: 17px;
    font-weight: bold;
  }

  .tip {
    display: flex;
    align-items: center;
    color: #666666;
  }
}
</style>